//
//  ZYHouseEditVC.m
//  YiLin
//
//  Created by Zyark on 2018/6/1.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYHouseEditVC.h"
#import "ZYViewUtils.h"
#import "ZYHouse.h"
#import "ImageSelectTools.h"
#import "ZYHouseViewModel.h"
#import <BMKLocationkit/BMKLocationComponent.h>
#import <BMKLocationkit/BMKLocationAuth.h>

@interface ZYHouseEditVC ()<ImageSelectToolsDelegate,BMKLocationAuthDelegate,BMKLocationManagerDelegate>
@property(nonatomic,strong) UIImageView *houseImageView;
//点击添加住宅图片
@property(nonatomic,strong) UILabel *addImageLabel;
@property(nonatomic,strong) UITextField *nameTextField;
@property(nonatomic,strong) UITextField *addressTextField;
@property(nonatomic,strong) UITextField *detailTextField;
@property(nonatomic,strong) UILabel *statusLabel;
@property(nonatomic,strong) UISwitch *statusSwitch;
@property(nonatomic,strong) UILabel *selectLabel;
@property(nonatomic,strong) ZYChangeLanguage *language;
@property(nonatomic,strong) UIButton *confirmBtn;
@property(nonatomic,strong) ImageSelectTools *imageSelectTools;

/**
 定位
 */
@property(nonatomic,strong) BMKLocationManager *locationManager;

/**
 经度
 */
@property(nonatomic,assign) CLLocationDegrees longitude;

/**
 纬度
 */
@property(nonatomic,assign) CLLocationDegrees latitude;

/**
 住宅编辑
 */
@property(nonatomic,strong) ZYHouseViewModel *viewModel;

/**
 图片数据
 */
@property(nonatomic,strong) NSData *imageData;
@end

@implementation ZYHouseEditVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(_type == ZYModifyHouseTypeAdd){
        self.title = [_language getStringByKey:LC_ME_MAIN_HOUSE_ADD];
    }else{
        self.title = [_language getStringByKey:LC_ME_MAIN_HOUSE_EDIT];
    }
    @weakify(self)
    [_locationManager requestLocationWithReGeocode:YES withNetworkState:YES completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
        @strongify(self)
        if (error){
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            self.longitude = 0;
            self.latitude = 0;
        }
        if(location){
            if (location.location) {
                CLLocationCoordinate2D coordinate = location.location.coordinate;
                self.longitude = coordinate.longitude;
                self.latitude = coordinate.latitude;
                NSLog(@"longitude:%f latitude%f",coordinate.longitude,coordinate.latitude);
            }
        }
    }];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _locationManager = nil;
}


#pragma mark - init
-(void)setup{
    _language = [ZYChangeLanguage sharedZYChangeLanguage];
    [self setupTap];
    [self setupView];
    if(_house){
        [self setupData];
    }
    [self setupLocation];
    [self bindView];
}

-(void)bindView{
    @weakify(self);
    //添加
    [self.viewModel.addCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        //添加成功
        [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_ADD_HOUSE_SUCCESS]];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [self.viewModel.addCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:nil controller:self];
    }];
    //监听状态
    [[self.viewModel.addCommand.executing skip:1] subscribeNext:^(id x) {
        BOOL executing = [x boolValue];
        [[ToastHelper sharedToastHelper] setSimleProgressVisiable:executing];
    }];
    
    //修改
    [self.viewModel.modifyCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        //修改成功
        [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_MODIFY_HOUSE_SUCCESS]];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    //监听状态
    [[self.viewModel.modifyCommand.executing skip:1] subscribeNext:^(id x) {
        BOOL executing = [x boolValue];
        [[ToastHelper sharedToastHelper] setSimleProgressVisiable:executing];
    }];
    [self.viewModel.modifyCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:nil controller:self];
    }];
}

-(void)setupLocation{
//    [[BMKLocationAuth sharedInstance] checkPermisionWithKey:@"7Gqyr0o4Z2wWeBGPZDw4dieGeNGWEkrk" authDelegate:self];
    //初始化实例
    _locationManager = [[BMKLocationManager alloc] init];
    //设置delegate
    _locationManager.delegate = self;
    //设置返回位置的坐标系类型
    _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
    //设置距离过滤参数
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    //设置预期精度参数
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置应用位置类型
    _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
    //设置是否自动停止位置更新
    _locationManager.pausesLocationUpdatesAutomatically = YES;
    //设置是否允许后台定位
    _locationManager.allowsBackgroundLocationUpdates = NO;
    //设置位置获取超时时间
    _locationManager.locationTimeout = 10;
    //设置获取地址信息超时时间
    _locationManager.reGeocodeTimeout = 10;
}

-(void)setupView{
    CGFloat houseImageWidth = 60;
    //住宅图片
    _houseImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, houseImageWidth, houseImageWidth)];
    [self.view addSubview:_houseImageView];
    _houseImageView.top = self.navigationView.bottom;
    _houseImageView.centerX = self.view.centerX;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doSelectImage)];
    [_houseImageView addGestureRecognizer:tap];
    [_houseImageView setImage:[UIImage imageNamed:@"ic_me_info_add_house"]];
    _houseImageView.layer.cornerRadius = _houseImageView.width / 2;
    _houseImageView.layer.masksToBounds = YES;
    _houseImageView.userInteractionEnabled = YES;
    
    //添加图片提示
    _addImageLabel = [[UILabel alloc] init];
    _addImageLabel.size = CGSizeMake(ZYSCREEN_W - 30, 30);
    _addImageLabel.textAlignment = NSTextAlignmentCenter;
    _addImageLabel.textColor = RGBA(204, 204, 204, 1);
    _addImageLabel.font = [UIFont systemFontOfSize:12];
    if(_type == ZYModifyHouseTypeAdd){
        _addImageLabel.text = [_language getStringByKey:LC_ME_MAIN_HOUSE_ADD_HOUSE_IMAGE_LABEL];
    }else{
        _addImageLabel.text = [_language getStringByKey:LC_ME_MAIN_HOUSE_EDIT_HOUSE_IMAGE_LABEL];
    }
    [self.view addSubview:_addImageLabel];
    _addImageLabel.centerX = _houseImageView.centerX;
    _addImageLabel.top = _houseImageView.bottom + 3;
    
    CGFloat left = 15;
    CGFloat height = 40;
    CGFloat padding = 10;
    //名称
    _nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W - left * 2, height)];
    [self.view addSubview:_nameTextField];
    _nameTextField.top = _addImageLabel.bottom + 20;
    _nameTextField.centerX = self.view.centerX;
    [self setupLeftViewTextFiled:_nameTextField withTitle:[_language getStringByKey:LC_ME_MAIN_HOUSE_LIST_NAME_LABEL]];
    [self setupLine:_nameTextField];
    _nameTextField.placeholder = [_language getStringByKey:LC_ME_MAIN_HOUSE_ADD_NAME_PLACEHOLDER];
    
    //地址
    _addressTextField = [[UITextField alloc] initWithFrame:_nameTextField.bounds];
    [self.view addSubview:_addressTextField];
    _addressTextField.top = _nameTextField.bottom + padding;
    _addressTextField.centerX = self.view.centerX;
    [self setupLeftViewTextFiled:_addressTextField withTitle:[_language getStringByKey:LC_ME_MAIN_HOUSE_LIST_ADDRESS_LABEL]];
    [self setupLine:_addressTextField];
//    [self setupRightViewTextField:_addressTextField];
    
    //详细地址
//    _detailTextField = [[UITextField alloc] initWithFrame:_nameTextField.bounds];
//    [self.view addSubview:_detailTextField];
//    _detailTextField.top = _addressTextField.bottom + padding;
//    _detailTextField.centerX = self.view.centerX;
//    _detailTextField.placeholder = [_language getStringByKey:LC_ME_MAIN_HOUSE_ADD_ADDRESS_DETAIL_PLACEHOLDER];
//    [self setupLine:_addressTextField];
    
    //管理状态
    _statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 35)];
    _statusLabel.textColor = kLabelColor;
    _statusLabel.font = [UIFont systemFontOfSize:16];
    _statusLabel.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:_statusLabel];
    _statusLabel.top = _addressTextField.bottom + padding;
    _statusLabel.left = _addressTextField.left;
    _statusLabel.text = [_language getStringByKey:LC_ME_MAIN_HOUSE_LIST_STATUS_LABEL];
    
    _statusSwitch = [[UISwitch alloc] init];
    [_statusSwitch setOnTintColor:kMainColor];
    [self.view addSubview:_statusSwitch];
    _statusSwitch.top = _statusLabel.top;
    _statusSwitch.right = _addressTextField.right;
    
    _confirmBtn = [ZYViewUtils setupConfirmBtn];
    [self.view addSubview:_confirmBtn];
    if(_type == ZYModifyHouseTypeAdd){
        [_confirmBtn setTitle:[_language getStringByKey:LC_ME_MAIN_HOUSE_ADD_CONFIRM_BTN_TITLE] forState:UIControlStateNormal];
    }else{
        [_confirmBtn setTitle:[_language getStringByKey:LC_ME_MAIN_HOUSE_EDIT_CONFIRM_BTN_TITLE] forState:UIControlStateNormal];
    }
    _confirmBtn.centerX = self.view.centerX;
    _confirmBtn.top = _statusLabel.bottom + 25;
    [_confirmBtn addTarget:self action:@selector(confirmModify:) forControlEvents:UIControlEventTouchUpInside];
//    _statusLabel.le
}

-(void)setupData{
    _nameTextField.text = _house.name;
    _addressTextField.text = _house.address;
    _detailTextField.text = _house.detailAddress;
    [_statusSwitch setOn:(_house.state == ZYStatusOpenTypeOn)];
    [_houseImageView setImageURL:[NSURL URLWithString:_house.houseImageUrl]];
}

/**
 初始化textField左边Label
 @param textField textField
 @param tiitle 标题
 */
-(void)setupLeftViewTextFiled:(UITextField *)textField withTitle:(NSString *)tiitle{
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 35)];
    leftLabel.textColor = kLabelColor;
    leftLabel.font = [UIFont systemFontOfSize:16];
    leftLabel.textAlignment = NSTextAlignmentLeft;
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.leftView = leftLabel;
    leftLabel.text = tiitle;
    NSDictionary *attributes = @{NSFontAttributeName:leftLabel.font,};
    CGSize textSize = [tiitle boundingRectWithSize:CGSizeMake(200 , leftLabel.height)
                                                options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
    leftLabel.width = textSize.width + 20;
}


/**
 设置TextField右边视图
 @param textField textField
 */
-(void)setupRightViewTextField:(UITextField *)textField{
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, textField.height)];
    UIImageView *rightImageView =[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_public_right"]];
    [rightView addSubview:rightImageView];
    rightImageView.size = CGSizeMake(9, 15);
    rightImageView.right = rightView.right;
    rightImageView.centerY = rightView.centerY;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 70, 35)];
    label.textColor = RGBA(153, 153, 153, 1);
    label.font = [UIFont systemFontOfSize:14];
    label.textAlignment = NSTextAlignmentRight;
    label.text = [_language getStringByKey:LC_ME_MAIN_HOUSE_ADD_ADDRESS_SELECT_PLACEHOLDER];
    label.hidden = YES;
    [rightView addSubview:label];
    label.right = rightImageView.left - 8;
    label.centerY = rightView.centerY;
    
    textField.rightViewMode = UITextFieldViewModeAlways;
    textField.rightView = rightView;
    _selectLabel = label;
}


/**
 视图下面的线
 @param view view
 */
-(void)setupLine:(UIView *)view{
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = RGBA(235, 235, 235, 1);
    [self.view addSubview:line];
    line.left = view.left;
    line.width = ZYSCREEN_W - 2* line.left;
    line.top = view.bottom;
}

#pragma mark 确认
-(void)confirmModify:(id)button{
    [self dismissKeyboard];
    ZYHouse *house = [[ZYHouse alloc] init];
    house.address = _addressTextField.text;
    house.name = _nameTextField.text;
    house.longitude = [NSString stringWithFormat:@"%f",_longitude];
    house.latitude = [NSString stringWithFormat:@"%f",_latitude];
    house.isManage = [_statusSwitch isOn];
    house.imageData = _imageData;
    if(_type == ZYModifyHouseTypeAdd){
        [self.viewModel addHouse:house];
    }else{
        house.houseId = _house.houseId;
        [self.viewModel modifyHouse:house];
    }
}

-(void)doSelectImage{
    [self.imageSelectTools alertSelectImage:self];
}

#pragma mark - Getter
-(ImageSelectTools *)imageSelectTools{
    if(!_imageSelectTools){
        _imageSelectTools = [[ImageSelectTools alloc] init];
        _imageSelectTools.delegate = self;
    }
    return _imageSelectTools;
}

-(ZYHouseViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[ZYHouseViewModel alloc] init];
    }
    return _viewModel;
}

#pragma mark - ImageSelectToolsDelegate
-(void)imageSelectTools:(ImageSelectTools *)imageSelectTools selectImage:(UIImage *)image imageData:(NSData *)data{
    _houseImageView.image = image;
    _imageData = data;
}
@end
